package com.wj.console.common.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;

public class ImageUtil {
	private final static int BYTE_ARRAY_LENGTH=8192;
	/**
	* @Description: 上传图片 
	* @param file 图片文件
	* @param request 请求
	* @param path 生成图片路径
	* @return
	* @return String    返回图片路径
	* @throws
	 */
	public static String uploadImg(MultipartFile file, HttpServletRequest request,String path){
		if(file==null){
			return null;
		}
		File tmpFile=null;
		//得到工程目录 
		String programPath = request.getSession().getServletContext().getRealPath("");
		//返回图片路径
		String imgPath = path + File.separator + file.getOriginalFilename();
		//拼接图片保存路径
		String fullPath  = programPath + File.separator + imgPath;
		
		tmpFile = new File(fullPath);
		if(!tmpFile.getParentFile().exists()) {
			tmpFile.getParentFile().mkdirs();
		}
		
		FileOutputStream os=null;
		InputStream in = null;
		try {
			os = new FileOutputStream(fullPath);
			in = file.getInputStream();
			byte buffer[] = new byte[BYTE_ARRAY_LENGTH];
			int b = 0;
	        while((b=in.read(buffer))!=-1){ //读取文件 
	          os.write(buffer, 0,b);
	        }
	        os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(os != null){
				try {
					os.close();
				} catch (IOException e) {
				}
			}
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
		//返回图片路径
		return imgPath;
	}
}
